<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text"  v-model='name'/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="uage" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="obj in arr" :key="obj.id">
          <td>{{obj.id}}</td>
          <td>{{obj.uname}}</td>
          <td>{{obj.age}}</td>
          <td>{{obj.gender}}</td>
          <td>
            <button @click="delFn(obj.id)">删除</button>
            <button @click="editFn(obj.id)" >编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: JSON.parse(localStorage.getItem('newArr',))||[],
      name:'',
      uage:0,
      sex:'',
      satus:false,
      num:0
    };
  },
  methods:{
    addFn(){
      // 新增
     if(!this.status){
        if(this.name.trim().length===0
      ||this.uage===''
      ||this.sex.trim().length===0
    ) return alert('请重新输入，不符合规范哦')
     this.arr.push({
       id:this.arr.length?this.arr.at(-1).id+1:1,
       uname:this.name,
       age:this.uage,
       gender:this.sex, 
     })
    //  修改
     }else{
      const index=this.arr.findIndex(item=>item.id===this.num)
      this.arr.splice(index,1,{id:index+1,
      uname:this.name,
      age:this.uage,
      gender:this.sex, })
      this.status=false
     }
      this.name='',
     this.uage=0
     this.sex=''
    },
    // 删除
    delFn(id){
     this.arr=this.arr.filter(item=>item.id!==id)
    },
    // 编辑
    editFn(id){
      this.num=id
     const index= this.arr.findIndex(item=>item.id===id)
     this.name=this.arr[index].uname,
     this.uage=this.arr[index].age,
     this.sex=this.arr[index].gender,
     this.status=true
    }
  },
  // 监听
  watch:{
    arr:{
      handler(){
       localStorage.setItem('newArr',JSON.stringify(this.arr))
      },
      deep:true
    }
  }
};
</script>
